package com.lagou.edu.mvcframework.components;

import com.lagou.edu.mvcframework.pojo.ModelAndView;
import com.lagou.edu.mvcframework.utils.FreemarkerUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class ViewResolver {
    public static void resolve(HttpServletRequest req, HttpServletResponse resp,Object result){
        String realPath = req.getServletContext().getRealPath("/WEB-INF/");
        if (result instanceof ModelAndView){
            ModelAndView modelAndView = (ModelAndView) result;
            String view = modelAndView.getView();
            Map<String,Object> model = modelAndView.getModel();
            try {
                FreemarkerUtil.initConfig(FreemarkerUtil.TEMPLATE_LOADING_FILE,realPath);
                String html = FreemarkerUtil.printString(view,model);
                resp.getWriter().write(html);
                resp.setContentType("text/html;charset=UTF-8");
            }catch (Exception e){

            }

        }
    }

}
